import React from 'react'
import {
  BaseListPage,
  IBaseListPageState,
  IBaseListPageProps,
  columnRenders,
  UdModal,
  http,
  UdModalForm,
  validators,
} from '@/lib'
import apis from '@/apis/SystemSettings'
import { message, Button, Select } from 'antd'
import _ from 'lodash'
import { http as speciHttp } from '@/utils/specialHttp'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'

const { Option } = Select

const UpdateBtnAuth = 'workflow_manage_put'

export default class Index extends BaseListPage<IApprovalProcessListProps, IApprovalProcessListState> {
  protected saveParamsWithUrl = true
  // 账号只有一个品牌，才可进入流程管理
  // public canViewFlowSystem = udMainStore.brandList && udMainStore.brandList.length === 1
  //2021-11-29 管理员也需要进入流程管理
  public canViewFlowSystem = udMainStore.brandList && udMainStore.brandList.length >= 1
  public brandList = udMainStore.brandList
  constructor(props) {
    super(props)
    this.state = {
      title: '审批流程管理',
      queryApi: apis.ApprovalProcessPage,
      method: 'GET',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
        },
        {
          label: '经销商门户系统流程KEY',
          id: 'processKey',
        },
      ],
      columns: [
        { title: '审批流程名称', dataIndex: 'processName' },
        { title: '经销商门户系统流程KEY', dataIndex: 'processKey' },
        { title: '流程引擎系统流程KEY', dataIndex: 'processDefKey' },
        { title: '创建人', dataIndex: 'createName' },
        { title: '创建时间', dataIndex: 'createTime' },
        { title: '修改人', dataIndex: 'updateName' },
        { title: '修改时间', dataIndex: 'updateTime' },
        {
          title: '操作',
          dataIndex: 'oprate',
          width: '80px',
          render: columnRenders.operate([
            { title: '编辑', auth: UpdateBtnAuth, action: (text, model) => this.editHandle(model) },
          ]),
        },
      ],
      rowKey: 'processDefKey',
      leftBtns: [
        <Button type="primary" onClick={this.handAddProcess}>
          新增
        </Button>,
        this.canViewFlowSystem && (
          <Button type="primary" onClick={this.processManageHandle}>
            流程管理
          </Button>
        ),
        <Button type="primary" onClick={this.onRefresh}>
          刷新缓存
        </Button>,
      ],
      tableProps: {
        rowKey: 'processKey',
        rowSelection: null,
      },
      processKeyOptions: [],
    }
  }

  componentDidMount() {
    super.componentDidMount()
    this.getProcessKeyList()
  }

  public getProcessKeyList = () => {
    const tenantId = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile?.brandCode
    speciHttp.get(apis.ProcessKeySelectData + tenantId).then(res => {
      const processKeyOptions = res.data?.map(({ key: value, name: title }) => ({ value, title }))
      this.setState({
        processKeyOptions,
      })
    })
  }

  private handAddProcess = () => {
    let {
      conditions: { brandCode },
    } = this.queryParams
    UdModal.open({
      title: '新增',
      width:'650px',
      content: (
        <UdModalForm
          labelCol={{ span: 6 }}
          items={[
            {
              id: 'brandCode',
              label: '品牌公司',
              initialValue: brandCode,
              render: <UdSelect showSearch allowClear={false} options={this.brandList} />,
              rules: [validators.required],
            },
            { id: 'processName', label: '审核流程名称', rules: [validators.required] },
            { id: 'processKey', label: '经销商门户系统流程KEY', rules: [validators.required] },
            {
              id: 'processDefKey',
              label: '流程引擎系统流程KEY',
              rules: [validators.required],
              render: (
                <Select showSearch optionFilterProp="children">
                  {this.state.processKeyOptions.map(({ value, title }) => (
                    <Option value={value}>{title}</Option>
                  ))}
                </Select>
              ),
            },
          ]}
        />
      ),
      onOk: values => {
        let params = values
        params.type = 1 //新增type为1  不传为编辑
        return http.put(apis.EditApprovalProcess, params).then(res => {
          this.query()
          message.success('新增成功')
        })
      },
    })
  }

  public editHandle = row => {
    const { processName, processKey, brandName, brandCode } = row
    const formLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
    }
    UdModal.open({
      title: '编辑',
      content: (
        <UdModalForm
          {...formLayout}
          items={[
            { id: 'brandName', label: '品牌公司', render: <div>{brandName}</div> },
            { id: 'processName', label: '审批流程名称', render: <div>{processName}</div> },
            { id: 'processKey', label: '经销商门户系统流程KEY', render: <div>{processKey}</div> },
            {
              id: 'processDefKey',
              label: '流程引擎系统流程KEY',
              rules: [validators.required],
              render: (
                <Select showSearch optionFilterProp="children">
                  {this.state.processKeyOptions.map(({ value, title }) => (
                    <Option value={value}>{title}</Option>
                  ))}
                </Select>
              ),
            },
          ]}
          values={row}
        />
      ),
      onOk: values => {
        let params = values
        params.brandCode = brandCode
        return http.put(apis.EditApprovalProcess, params).then(res => {
          this.query()
          message.success('编辑成功')
        })
      },
    })
  }

  public onRefresh = () => {
    http.post(apis.refreshRedis, {}).then(res => {
      message.success('刷新成功')
    })
  }

  public processManageHandle = () => {
    let {
      conditions: { brandCode },
    } = this.queryParams
    if (udMainStore.brandList && udMainStore.brandList.length === 1) {
      this.props.history.push('/systemsettings/approvalProcess/processmanage')
    } else {
      this.props.history.push('/systemsettings/approvalProcess/processmanage?defaultBrandValue=' + brandCode)
    }
  }
}

interface IApprovalProcessListState extends IBaseListPageState {
  processKeyOptions: any[]
}

interface IApprovalProcessListProps extends IBaseListPageProps {}
